package uutalk.netcloud.talk.base.util.thirdpart;

import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;

import uutalk.netcloud.talk.base.util.MD5;

/**
 * Created by hujie on 2017/10/20.
 *
 * 文件下载管理
 */

public class FileDownloadManager {

    private static FileDownloadManager INSTANCE;
    public static final String VOICE_FILE_TYPE = "downloadVoice";


    public static FileDownloadManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new FileDownloadManager();
        }
        return INSTANCE;
    }

    private FileDownloadManager() {

    }


    /**
     * 获取文件下载缓存路径
     * @return
     */
    private String getDownloadCacheDir(String type) {
        String fileDir = FileDownloadUtils.getDefaultSaveRootPath();
        if (fileDir != null) {
            return fileDir + File.separator + type;
        }
        return null;
    }


    /**
     * 根据远程URL获取本地下载的路径
     * @param key
     */
    public String getLocalPathByUrl(String key) {
        String dir = getDownloadCacheDir(VOICE_FILE_TYPE);
        if (dir != null) {
            String md5Path = MD5.md5(key);
            File file = new File(dir, md5Path);
            if (file.exists()) {
                return file.getPath();
            }
        }
        return null;
    }

    /**
     * 下载语音
     * @param url
     */
    public void downloadVoice(String key, String url, FileDownloadListener downloadListener) {


        String dir = getDownloadCacheDir(VOICE_FILE_TYPE);
        if (dir != null) {
            String md5Path = MD5.md5(key);
            String path = dir + File.separator + md5Path;
            FileDownloader.getImpl()
                    .create(url)
                    .setPath(path)
                    .setCallbackProgressIgnored()
                    .setAutoRetryTimes(2)
                    .setWifiRequired(true)
                    .setListener(downloadListener)
                    .start();
        }

    }


}
